﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using EOSCRM.Util ;
using EOSCRM.Domain;
using EOSCRM.Web.Common;
using EOSCRM.Dao;
using EOSCRM.Web.Shared;
using EOSCRM.Web.UserControls;


namespace EOSCRM.Web.Forms.ChucNang
{
    public partial class QLTinhTrang : Authentication
    {
        private readonly CayDao _objDao = new CayDao();
        private readonly LoDao _loDao = new LoDao();
        private readonly NhanVienDao _nvDao = new NhanVienDao();
        private readonly KhuVucDao _khuVucDao = new KhuVucDao();
        private readonly TinhTrangCayDao _tinhtrangcayDao = new TinhTrangCayDao();
        private readonly ThayDoiTinhTrangDao _thaydoitinhtrangcayDao = new ThayDoiTinhTrangDao();
        private static bool _tinhtrangcayBanDau = new bool();

        private string CreateID()
        {
            string ma = "";
            ma = ma + "C";
            ma = ma + DateTime.Now.Day.ToString("D2") + DateTime.Now.Month.ToString("D2") + DateTime.Now.Year.ToString("D4") + DateTime.Now.Hour.ToString("D2") + DateTime.Now.Minute.ToString("D2") + DateTime.Now.Second.ToString("D2");
            return ma;
        }

        private CAY ItemObj
        {
            get
            {
                if (!ValidateData())
                    return null;

                var kv = new CAY
                {
                   MaCay = lbma.Text.Trim(),
                   Hang = int.Parse(txthang.Text.Trim()),
                   Cot = int.Parse(txtcot.Text.Trim()),
                   MaLo = ddlLo.SelectedValue,
                   TinhTrang = ddltinhtrang.SelectedValue

                    //STARTCODE = txtMaKV.Text.Trim(),
                    //DACBIET = false
                };

                return kv;
            }
        }
        private THAYDOITINHTRANG ItemTTObj
        {
            get
            {
                if (!ValidateData())
                    return null;
                var lo = _loDao.Get(ddlLo.SelectedValue);
                var kv = new THAYDOITINHTRANG
                {
                    NgayGhiNhan=DateTime.Now,
                    MaMKN=CreateID(),
                    MaCay = lbma.Text.Trim(),                 
                    TinhTrang = ddltinhtrang.SelectedValue,
                    NguyenNhan=txtnguyennhan.Text.Trim(),
                    MaNV = ddlNhanVien.SelectedValue,
                    CayTrong = lo.SoTrong,
                    CayChoMu = lo.SoChoMu,
                    CayKhongChoMu = lo.SoKhongChoMu,
                    TBMu1Ngay = lo.TBMu1Ngay,
                    TBMu1Thang = lo.TBMu1Thang
                    //STARTCODE = txtMaKV.Text.Trim(),
                    //DACBIET = false
                };

                return kv;
            }
        }

        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }
            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    ClearForm();
                    lbngayhientai.Text = DateTime.Now.ToString("dd/MM/yyyy"); 
                    LoadKhuVuc();
                    LoadLo(ddlKhuVuc.SelectedValue);
                    LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).HasValue ? ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value : DateTime.Now);
                    LoadCayLo(ddlLo.SelectedValue);
                    LoadTinhTrang();
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        
        private void BindDataForGrid()
        {
            var objList = _objDao.GetList(ddlLo.SelectedValue);
            gvList.DataSource = objList;
            gvList.PagerInforText = objList.Count.ToString();
            gvList.DataBind();
        }
        
        public bool ValidateData()
        {
            if (ddlLo.SelectedIndex == -1)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Lô"), ddlLo.ClientID);
                return false;
            }
            if (ddlNhanVien.SelectedIndex == -1)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Nhân viên"), ddlNhanVien.ClientID);
                return false;
            }

            try
            {
                int.Parse(txthang.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Hàng"), txthang.ClientID);
                return false;
            }

            try
            {
                int.Parse(txtcot.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Cot"), txtcot.ClientID);
                return false;
            }

            return true;
        }

      

        private void ClearForm()
        {
            lbma.Text = CreateID();
            txthang.Text = "0";
            txtcot.Text = "0";
            txtnguyennhan.Text = "";
            SetReadonly(txthang.ClientID, false);
            SetReadonly(txtcot.ClientID, false);
            txtngay.Text = DateTime.Now.ToString();
            UpdateMode = Mode.Create;
            ddlLo.Focus();
        }

        private void BindKhuVuc(CAY obj)
        {
            if (obj == null)
                return;
            SetControlValue(txthang.ClientID, obj.Hang.ToString());
            SetControlValue(txtcot.ClientID, obj.Cot.ToString());      
            SetControlValue(ddltinhtrang.ClientID, obj.TinhTrang);
            SetReadonly(txthang.ClientID, true);
            SetReadonly(txtcot.ClientID, true);
            lbma.Text = obj.MaCay;

            var td = _thaydoitinhtrangcayDao.Get(obj.MaCay);
            if (td == null)
                return;
            SetControlValue(txtngay.ClientID, td.NgayGhiNhan.ToString());
            SetControlValue(txtnguyennhan.ClientID, td.NguyenNhan);
            SetControlValue(ddlNhanVien.ClientID, td.MaNV);
           
            upnlInfor.Update();
            _tinhtrangcayBanDau = obj.TINHTRANGCAY.KhaNangChoMu;
        }
        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var makv = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditItem":
                        if (!string.Empty.Equals(makv))
                        {
                            var objDb = _objDao.Get(makv);
                            if (objDb != null)
                            {
                                BindKhuVuc(objDb);
                                UpdateMode = Mode.Update;
                            }
                        }

                        CloseWaitingDialog();

                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var infotd = ItemTTObj;
            var info = ItemObj;
            if (info == null || infotd == null)
            {
                CloseWaitingDialog();
                return;
            }

            Message msg=null;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                var tontai = _objDao.Get(info.MaLo, info.Hang, info.Cot);
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Cây đã tồn tại");
                    return;
                }
                msg = _objDao.Insert(info);
                if (msg.MsgType != MessageType.Error)
                {
                  
                        CapNhatCayTrongNew(info.TINHTRANGCAY.KhaNangChoMu);
                   
                }
                _thaydoitinhtrangcayDao.Insert(infotd);
                
            }
            // update
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                
                msg = _objDao.Update(info);
                if (msg.MsgType != MessageType.Error)
                {
                    var tt = _tinhtrangcayDao.Get(info.TinhTrang);
                    CapNhatCayTrongUp(_tinhtrangcayBanDau, tt.KhaNangChoMu);
                   
                }
                _thaydoitinhtrangcayDao.Insert(infotd);                
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
               
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();

                // Refresh grid view
                BindDataForGrid();
                
                upnlGrid.Update();
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }

        private void CapNhatCayTrongUp(bool _tinhtrangBanDau, bool p)
        {
            if (_tinhtrangBanDau == false && p == true)
            {
                var lo = _loDao.Get(ddlLo.SelectedValue);
                lo.SoChoMu = lo.SoChoMu + 1;
                lo.SoKhongChoMu = lo.SoKhongChoMu - 1;
                _loDao.UpdateTT(lo);
            }
            if (_tinhtrangBanDau == true && p == false)
            {
                var lo = _loDao.Get(ddlLo.SelectedValue);
                lo.SoChoMu = lo.SoChoMu - 1;
                lo.SoKhongChoMu = lo.SoKhongChoMu + 1;
                _loDao.UpdateTT(lo);
            }
        }

        private void CapNhatCayTrongNew(bool p)
        {
            if (p == false)
            {
                var lo = _loDao.Get(ddlLo.SelectedValue);
                lo.SoChoMu = lo.SoChoMu - 1;
                lo.SoKhongChoMu = lo.SoKhongChoMu + 1;
                _loDao.UpdateTT(lo);
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                DeleteList();
                BindDataForGrid();
                upnlGrid.Update();

                CloseWaitingDialog();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void DeleteList()
        {
            try
            {
                // Get list of ids that to be update
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    //TODO: check relation before update list

                    var objs = new List<CAY>();
                    var listIds = strIds.Split(',');

                    // Kiem tra relation ship truoc khi delete
                    foreach (var ma in listIds)
                    {
                        if (_objDao.IsInUse(ma))
                        {
                            var msgIsInUse = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Info, "thu hoạch với mã", ma);

                            CloseWaitingDialog();

                            ShowError(ResourceLabel.Get(msgIsInUse));
                            return;
                        }
                    }

                    //Add ma vao danh sách cần delete
                    objs.AddRange(listIds.Select(ma => _objDao.Get(ma)));

                    if (objs.Count > 0)
                    {
                        var msg = _objDao.DeleteList(objs);
                        if (msg != null)
                        {
                            CloseWaitingDialog();

                            switch (msg.MsgType)
                            {
                                case MessageType.Error:
                                    ShowError(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Info:
                                    ShowInfor(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Warning:
                                    ShowWarning(ResourceLabel.Get(msg));
                                    break;
                            }
                        }
                    }
                    else
                    {
                        CloseWaitingDialog();
                    }
                }
                ClearForm();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseWaitingDialog();
            ClearForm();
        }

        private void LoadNhanVienLo(string ma, DateTime ngay)
        {
            var objList = _nvDao.GetListLo(ma);
            CommonFunc.BindDropDownList(ddlNhanVien, objList, "TenNV", "MaNV", false);
        }

        private void LoadTinhTrang()
        {
            var objList = _tinhtrangcayDao.GetList();
            CommonFunc.BindDropDownList(ddltinhtrang, objList, "TenTinhTrang", "MaTinhTrang", false);
        }

        private void LoadKhuVuc()
        {
            var objList = _khuVucDao.GetList();
            CommonFunc.BindDropDownList(ddlKhuVuc, objList, "TenKhuVuc", "MaKhuVuc", false);
        }
        private void LoadLo(string makv)
        {
            var objList = _loDao.GetListKhuVuc(makv);
            CommonFunc.BindDropDownList(ddlLo, objList, "TenLo", "MaLo", false);
        }

        private void LoadCayLo(string malo)
        {
            var objList = _objDao.GetList(malo);
            gvList.DataSource = objList;
            gvList.DataBind();
        }

        protected void ddlKhuVuc_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadLo(ddlKhuVuc.SelectedValue);
            LoadCayLo(ddlLo.SelectedValue);
            LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            upnlGrid.Update();
        }

        protected void ddlLo_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadCayLo(ddlLo.SelectedValue);
            LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            upnlGrid.Update();
        }

        protected void ddlNhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }
    }
}